<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix process-header flex width100p">
        <div class="title flex-auto">{{ processTitle }}<span class="ml10 sub-title">{{ subTitle }}</span></div>
        <div class="btn-list flex flex-row align-center mr20 fixed-btn">
          <el-button type="" size="mini" class="mr10" @click="backPage">
            返 回
          </el-button>
          <el-button v-if="workOrdeInfo.status != 0" type="warning" size="mini" class="mr10" :disabled="draftDisabled" @click="draftAction(processStructureValue.edges[0])">
            暂 存
          </el-button>
          <el-button
            v-for="(item, index) in processStructureValue.edges"
            v-show="item.source === processStructureValue.nodes[active].id &&
              workOrdeInfo.status != 0
            "
            :key="index"
            type="primary"
            size="mini"
            :disabled="submitDisabled"
            @click="submitAction(item)"
          >
            {{ item.label }}
          </el-button>
        </div>
      </div>
      <div class="text item">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="mb5" />
        <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
          <fm-generate-form
            v-show="(currentNode.hideTpls===undefined ||
              currentNode.hideTpls===null ||
              currentNode.hideTpls.indexOf(tplItem.id)===-1) && tplIndex == 0"
            :key="tplIndex"
            :ref="'generateForm-'+tplItem.id"
            :preview="currentNode.hideTpls===undefined ||
              currentNode.hideTpls===null ||
              currentNode.hideTpls.indexOf(tplItem.id)===-1?false:true"
            :remote="remoteFunc"
            :value="tplItem.form_data"
            :bq-trees="bqTrees"
            :data="tplItem.form_structure"
            :disabled="currentNode.readonlyTpls===undefined ||
              currentNode.readonlyTpls===null ||
              currentNode.readonlyTpls.indexOf(tplItem.id)===-1?null:true"
          >
            <durgTable v-if="processStructureValue.process.name == '药物不良反应事件' && models" key="suspectedDrug" slot="hyyy_blank" :data="models.suspectedDrug" type="suspectedDrug" size="small" @addDrugRow="addDrugRow" @delSuspectedDrug="delSuspectedDrug" @changeModels="changeModels" @openDrug="openDrug" />
            <durgTable v-if="processStructureValue.process.name == '药物不良反应事件' && models" slot="byyp_blank" key="togetherDrug" :data="models.togetherDrug" type="togetherDrug" size="small" @addDrugRow="addDrugRow" @delSuspectedDrug="delSuspectedDrug" @changeModels="changeModels" @openDrug="openDrug" />
            <div v-if="processStructureValue.process.name == '药物不良反应事件'" slot="blms_blank">
              <el-tag v-for="item in formOptions.textAreaTabs" :key="item.value" class="mb5 mr10 cursor-p" @click="requireDialogClick(item)">
                {{ item.label }}
              </el-tag>
              <el-form-item>
                <el-input v-model="models.ypblfygc" type="textarea" :placeholder="`请输入不良反应/事件过程描述`" name="ypblfygc" style="width: 90%;" maxlength="2000" show-word-limit :autosize="{ minRows: 8, maxRows: 400}" class="jane-textarea" />
              </el-form-item>
            </div>
            <div slot="sac_blank">
              <el-form-item label-width="150px" label="患者损害结果" required>
                <el-radio-group v-model="sjpg_slot_form.sjpg_shjg">
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="5"
                  >
                    轻微/无伤害
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="4"
                  >
                    轻度
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="3"
                  >
                    中度
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="2"
                  >
                    重度
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="1"
                  >
                    极重度
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="0"
                  >
                    死亡
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label-width="150px" label="事件再发生频率" required>
                <el-radio-group v-model="sjpg_slot_form.sjpg_zfspl">
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="0"
                  >
                    数周内
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="1"
                  >
                    一年数次
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="2"
                  >
                    1-2年1次
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="3"
                  >
                    2-5年1次
                  </el-radio>
                  <el-radio
                    class="incat-radio incat-mini"
                    :style="{
                      display:'inline-block'}"
                    :label="4"
                  >
                    五年以上
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label-width="150px" label="SAC评分" required>
                <el-input v-model="sjpg_slot_form.sjpg_sac" :style="{ width: '150px' }" />
              </el-form-item>
            </div>
          </fm-generate-form>
        </template>
      </div>
      <hr style="background-color: #d9d9d9; border:0; height:1px;margin-bottom: 50px;">
      <!-- <div class="text item" style="text-align: center;margin-top:18px">
        <el-button
          v-for="(item, index) in processStructureValue.edges"
          v-show="item.source===processStructureValue.nodes[active].id"
          :key="index"
          type="primary"
          :disabled="submitDisabled"
          @click="submitAction(item)"
        >
          {{ item.label }}
        </el-button>
      </div> -->
    </el-card>
    <require-dialog ref="requireDialog" :type="requireValue" @changeRequireStr="changeRequireStr" />
  </div>
</template>
<script>
import Vue from 'vue'
import {
  GenerateForm
} from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import durgTable from './components/ywblfy/drugTable'
import {
  processStructure,
  createWorkOrder,
  updateWorkOrder,
  draftWorkOrder,
  recallWorkOrder
} from '@/api/baqsj/work-order'
import { listAllUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList, bqDeptList } from '@/api/system/dept'
import requireDialog from './components/ywblfy/requireDialog'
import options from './components/ywblfy/options'
import { formatBqName } from '@/utils/bq.js'
export default {
  name: 'Edit',
  components: { durgTable, requireDialog },
  data() {
    return {
      bqTrees: [],
      zfsplRadio: {
        '0': '数周内',
        '1': '一年数次',
        '2': '1-2年1次',
        '3': '2-5年1次',
        '4': '五年以上'
      },
      shjgRadio: {
        '1': '极重度',
        '2': '重度',
        '3': '中度',
        '4': '轻度',
        '5': '轻微/无伤害'
      },
      models: {
        suspectedDrug: [],
        togetherDrug: [],
        ypblfygc: ''
      },
      sjpg_slot_form: {
        sjpg_shjg: '',
        sjpg_shjg_text: '',
        sjpg_zfspl_text: '',
        sjpg_zfspl: '',
        sjpg_sac: ''
      },
      requireValue: {},
      formOptions: options,
      list3: [],
      submitDisabled: false,
      active: 0,
      processTitle: '',
      subTitle: '',
      processId: '',
      processStructureValue: {},
      submitDisabled: false,
      workOrdeInfo: {
        id: null,
        status: 1
      },
      draftDisabled: false,
      tpls: [],
      newTpls: [],
      ruleForm: {
        title: '',
        priority: 1,
        priority_msg: '',
        hospital: '',
        apply_dept: '',
        process: '',
        classify: '',
        state: [],
        self_data: {},
        fsrq: '',
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          mobile_form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: []
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'blur' }
        ]
      },
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        },
        async bqTreeList(resolve) {
          const res = await bqDeptList()
          resolve(res.data)
        }
      }
    }
  },
  watch: {
    'sjpg_slot_form.sjpg_shjg': function(newVal) {
      this.sjpg_slot_form.sjpg_shjg_text = this.shjgRadio[newVal]
      console.log(this.sjpg_slot_form.sjpg_shjg_text)
      this.calculateScore()
    },
    'sjpg_slot_form.sjpg_zfspl': function(newVal) {
      this.sjpg_slot_form.sjpg_zfspl_text = this.zfsplRadio[newVal]
      console.log(this.sjpg_slot_form.sjpg_zfspl_text)
      this.calculateScore()
    }
  },
  async created() {
    this.processId = parseInt(this.$route.query.processId)
    this.ruleForm.workOrderId = parseInt(this.$route.query.workOrderId)
    await this.getBqTreeList()
    this.getProcessNodeList()
  },
  methods: {
    async getBqTreeList() {
      const res = await bqDeptList()
      if (res.data) {
        this.bqTrees = res.data
      }
    },
    calculateScore() {
      const sacMatrix = [
        [1, 1, 1, 1, 2],
        [1, 1, 2, 2, 3],
        [2, 2, 2, 3, 3],
        [3, 3, 3, 4, 4],
        [3, 4, 4, 4, 4],
        [4, 4, 4, 4, 4]
      ]
      this.sjpg_slot_form.sjpg_sac = sacMatrix[this.sjpg_slot_form.sjpg_shjg][this.sjpg_slot_form.sjpg_zfspl]
    },
    changeRequireStr(str) {
      this.models.ypblfygc = this.models.ypblfygc + str
    },
    requireDialogClick(value) {
      this.requireValue = value
      this.$refs.requireDialog.open(value)
    },
    openDrug() {

    },
    addDrugRow(type) {
      const id = new Date().getTime()
      console.log(type)
      this.models[type].push({
        num: id,
        approvalNum: '',
        name: '',
        niversalName: '',
        dosageFrom: '',
        prodFactory: '',
        prodBatch: '',
        dosage: '',
        dosageUnit: '',
        dosageDay: '',
        dosageRate: '',
        drugRoute: '',
        startDate: '',
        endDate: '',
        reason: ''
      })
    },
    delSuspectedDrug(row, type) {
      const index = this.models[type].findIndex((item) => item.num === row.num)
      if (index > -1) {
        this.models[type].splice(index, 1)
        this.list3.splice(this.list3.indexOf(row.drugId), 1)
      }
    },
    changeModels(num, selectDosage, type) {
      const list = this.models[type]
      if (list && list.length > 0) {
        list.forEach((item) => {
          if (item.num === num) {
            item.dosageFrom = selectDosage.join(',')
          }
        })
      }
      this.models[type] = JSON.parse(JSON.stringify(list))
    },
    backPage() {
      this.$router.push({ path: '/baqsj/apply', query: {}})
    },
    getProcessNodeList() {
      processStructure({
        processId: this.$route.query.processId,
        workOrderId: this.ruleForm.workOrderId
      }).then(response => {
        this.processStructureValue = response.data
        this.newTpls = response.data.tpls
        this.currentNode = this.processStructureValue.nodes[0]
        this.subTitle = this.processStructureValue.process.name
        this.processTitle = this.processStructureValue.process.category
        for (var itemTpl of this.newTpls) {
          if (itemTpl.form_data.hasOwnProperty('sjpg_shjg')) {
            this.sjpg_slot_form.sjpg_shjg = itemTpl.form_data.sjpg_shjg
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_shjg_text')) {
            this.sjpg_slot_form.sjpg_shjg_text = itemTpl.form_data.sjpg_shjg_text
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_zfspl_text')) {
            this.sjpg_slot_form.sjpg_zfspl_text = itemTpl.form_data.sjpg_zfspl_text
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_zfspl')) {
            this.sjpg_slot_form.sjpg_zfspl = itemTpl.form_data.sjpg_zfspl
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_sac')) {
            this.sjpg_slot_form.sjpg_sac = itemTpl.form_data.sjpg_sac
          }
          if (itemTpl.form_data.hasOwnProperty('suspectedDrug')) {
            this.models.suspectedDrug = itemTpl.form_data.suspectedDrug
          }
          if (itemTpl.form_data.hasOwnProperty('togetherDrug')) {
            this.models.togetherDrug = itemTpl.form_data.togetherDrug
          }
          if (itemTpl.form_data.hasOwnProperty('ypblfygc')) {
            this.models.ypblfygc = itemTpl.form_data.ypblfygc
          }
        }
      })
    },
    draftAction(item) {
      this.draftDisabled = true
      const stateMap = {}
      this.ruleForm.process = this.processId
      this.ruleForm.status = 1
      this.ruleForm.classify = this.processStructureValue.process.classify
      this.ruleForm.title = `${this.processTitle}-${this.subTitle}`
      stateMap['id'] = item.target
      this.ruleForm.source_state = this.processStructureValue.nodes[
        this.active
      ].label

      for (var v of this.processStructureValue.nodes) {
        if (v.id === item.target) {
          if (v.assignType !== undefined) {
            stateMap['process_method'] = v.assignType
          }
          if (v.assignValue !== undefined) {
            stateMap['processor'] = Array.from(new Set(v.assignValue))
          }
          stateMap['label'] = v.label
          stateMap['desc'] = v.desc
          break
        }
      }
      this.ruleForm.state = [stateMap]
      this.ruleForm.tpls = {
        form_name: [],
        form_structure: [],
        mobile_form_structure: [],
        form_data: [],
        mid: []
      }
      var promiseList = []
      this.tpls = []
      for (var tpl of this.newTpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
      }

      for (var tpl of this.processStructureValue.tpls) {
        // tpl.form_structure.id = tpl.id;
        this.ruleForm.tpls.form_structure.push(tpl.form_structure)
        this.ruleForm.tpls.mobile_form_structure.push(tpl.mobile_form_structure)
        this.ruleForm.tpls.form_name.push(tpl.form_name)
        this.ruleForm.tpls.mid.push(tpl.mid)
        promiseList.push(
          this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
        )
      }
      Promise.all(promiseList)
        .then(values => {
          this.ruleForm.source = this.processStructureValue.nodes[
            this.active
          ].id

          for (var item of values) {
            if (item.hasOwnProperty('hospital')) {
              this.ruleForm.hospital = item.hospital
            }
            if (item.hasOwnProperty('tbrqk_dept') && item.tbrqk_dept != '') {
              this.ruleForm.apply_dept = item.tbrqk_dept
            }
            if (item.hasOwnProperty('sjsx_patient_ward') && item.sjsx_patient_ward != '') {
              this.ruleForm.apply_dept = formatBqName(item.sjsx_patient_ward)
            }
            if (item.hasOwnProperty('tbrqk_fsrq')) {
              this.ruleForm.fsrq = new Date(item.tbrqk_fsrq)
            }
          }

          if (this.processStructureValue.process.name == '药物不良反应事件') {
            for (let i = 0; i < values.length; i++) {
              if (values[i].hasOwnProperty('blms_blank')) {
                // values[i] = { ...values[i], ...this.models, ...this.sjpg_slot_form }
                values[i] = { ...values[i], ...this.models }
                break
              }
            }
          }

          if (this.tpls.length > 0) {
            for (var tplDataIndex in this.tpls) {
              if (this.tpls[tplDataIndex].mid == 'ywblfy') {
                // values[tplDataIndex] = { ...values[tplDataIndex], ...this.models, ...this.sjpg_slot_form }
                values[tplDataIndex] = { ...values[tplDataIndex], ...this.models }
              }
              this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
            }
            this.ruleForm.newTpls = this.tpls
          }
          this.ruleForm.tpls.form_data = values
          this.ruleForm.is_exec_task = item.isExecuteTask
          this.ruleForm.self_data = this.sjpg_slot_form
          draftWorkOrder(this.ruleForm)
            .then(response => {
              if (response.code === 200) {
                console.log(response)
                this.$message({
                  type: 'success',
                  message: '暂存成功!'
                })
                this.workOrdeInfo = response.data.workOrder
                this.ruleForm.workOrderId = this.workOrdeInfo.id
                this.newTpls = response.data.tpls
                this.draftDisabled = false
              }
            })
            .catch(() => {
              this.draftDisabled = false
            })
        })
        .catch(() => {
          this.draftDisabled = false
        })
    },
    submitAction(item) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.submitDisabled = true
          var stateMap = {}
          this.ruleForm.process = parseInt(this.$route.query.processId)
          this.ruleForm.classify = this.processStructureValue.process.classify
          this.ruleForm.title = `${this.processTitle}-${this.subTitle}`
          stateMap['id'] = item.target
          this.ruleForm.source_state = this.processStructureValue.nodes[this.active].label
          for (var v of this.processStructureValue.nodes) {
            if (v.id === item.target) {
              if (v.assignType !== undefined) {
                stateMap['process_method'] = v.assignType
              }
              if (v.assignValue !== undefined) {
                stateMap['processor'] = Array.from(new Set(v.assignValue))
              }
              stateMap['label'] = v.label
              stateMap['desc'] = v.desc
              break
            }
          }
          this.ruleForm.state = [stateMap]

          this.ruleForm.tpls = {
            form_name: [],
            form_structure: [],
            mobile_form_structure: [],
            form_data: [],
            mid: []
          }
          // 绑定流程任务
          this.ruleForm.tasks = this.processStructureValue.process.task === undefined ? [] : this.processStructureValue.process.task
          // 追加节点任务
          if (this.processStructureValue.nodes[this.active].task !== undefined && this.processStructureValue.nodes[this.active].task.length > 0) {
            for (var task of this.processStructureValue.nodes[this.active].task) {
              if (this.ruleForm.tasks.indexOf(task) === -1) {
                this.ruleForm.tasks.push(task)
              }
            }
          }

          var promiseList = []

          this.tpls = []
          for (var tpl of this.newTpls) {
            this.tpls.push({
              tplDataId: tpl.id,
              tplId: tpl.form_structure.id
            })
          }

          for (var tpl of this.processStructureValue.tpls) {
            // tpl.form_structure.id = tpl.id;
            this.ruleForm.tpls.form_structure.push(tpl.form_structure)
            this.ruleForm.tpls.mobile_form_structure.push(tpl.mobile_form_structure)
            this.ruleForm.tpls.form_name.push(tpl.form_name)
            this.ruleForm.tpls.mid.push(tpl.mid)
            if (tpl.mid == 'baqsjcz' || tpl.mid == 'baqsjczyw' || tpl.mid == 'baqsjczqx') {
              promiseList.push(this.$refs['generateForm-' + tpl.id][0].getDataNoValidate())
            } else {
              promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
            }
          }

          Promise.all(promiseList).then(values => {
            this.ruleForm.source = this.processStructureValue.nodes[this.active].id
            for (var item of values) {
              if (item.hasOwnProperty('hospital')) {
                this.ruleForm.hospital = item.hospital
              }
              if (item.hasOwnProperty('tbrqk_dept') && item.tbrqk_dept != '') {
                this.ruleForm.apply_dept = item.tbrqk_dept
              }
              if (item.hasOwnProperty('sjsx_patient_ward') && item.sjsx_patient_ward != '') {
                this.ruleForm.apply_dept = formatBqName(item.sjsx_patient_ward)
              }
              if (item.hasOwnProperty('tbrqk_fsrq')) {
                this.ruleForm.fsrq = new Date(item.tbrqk_fsrq)
              }
              // 非常紧急的逻辑（发送给领导）
              if (item.hasOwnProperty('priority')) {
                if (item.priority == '是') {
                  this.ruleForm.priority = 3
                }
              }
              if (item.hasOwnProperty('priority_msg')) {
                this.ruleForm.priority_msg = item.priority_msg
              }
            }

            if (this.processStructureValue.process.name == '药物不良反应事件') {
              for (let i = 0; i < values.length; i++) {
                if (values[i].hasOwnProperty('blms_blank')) {
                // values[i] = { ...values[i], ...this.models, ...this.sjpg_slot_form }
                  values[i] = { ...values[i], ...this.models }
                  break
                }
              }
            }
            if (this.tpls.length > 0) {
              for (var tplDataIndex in this.tpls) {
                if (this.tpls[tplDataIndex].mid == 'ywblfy') {
                  // values[tplDataIndex] = { ...values[tplDataIndex], ...this.models, ...this.sjpg_slot_form }
                  values[tplDataIndex] = { ...values[tplDataIndex], ...this.models }
                }
                this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
              }
              this.ruleForm.newTpls = this.tpls
            }
            this.ruleForm.tpls.form_data = values
            this.ruleForm.is_exec_task = item.isExecuteTask
            this.ruleForm.self_data = this.sjpg_slot_form
            updateWorkOrder(this.ruleForm).then(response => {
              if (response.code === 200) {
                this.$message({
                  type: 'success',
                  message: '上报成功!'
                })
                localStorage.removeItem('baqsjPatient')
                this.$router.push({ path: '/baqsj/apply' })
              }
            }).catch(() => {
              this.submitDisabled = false
            })
          }).catch(() => {
            this.submitDisabled = false
          })
        }
      })
    }
  }
}

</script>
<style lang="scss" scoped>
.process-header {
  height: 50px;

  .title {
    font-size: 25px;
    font-weight: 600;

  }

  .sub-title {
    font-size: 19px;
    vertical-align: bottom;
    padding-left: 10px;
    color: #555;
  }
}

</style>
